<template>
  <div class="avatar-upload">
    <div class="avatar-preview" @click="openFileInput">
      <!-- 如果有选择的图片，显示预览；否则显示默认图标 -->
      <img v-if="selectedImage" :src="selectedImage" alt="Preview" class="preview-image" />
      <i v-else class="fa fa-camera"></i>
    </div>
    <div class="update" @click="updatePortrait">点击修改</div>
    <input type="file" accept="image/*" ref="fileInput" @change="handleFileChange" style="display: none;"  />
  </div>
</template>

<script>
import axios from 'axios';
import settings from '../../settings.json'
export default {
  data() {
    return {
      // 存储选择的图片的 URL
      selectedImage: '',
      user: null,
    };
  },
  created() {
    this.user = JSON.parse(localStorage.getItem("currentUser"))
    this.selectedImage = `${settings.ipAddress}/file/getPortrait/${this.user.username}` 
  },
  methods: {
    // 打开文件选择框
    openFileInput() {
      this.$refs.fileInput.click();
    },
    // 处理文件选择事件
    handleFileChange(e) {
      const file = e.target.files[0];
      if (file) {
        const reader = new FileReader();
        reader.onload = (event) => {
          this.selectedImage = event.target.result;
        };
        reader.readAsDataURL(file);
      }
    },
    updatePortrait() {
      // 实际应用中，将 this.selectedImage 上传到服务器
      // 上传成功后，将 this.selectedImage 保存到用户信息中
      // 上传失败时，恢复原头像
      let data = new FormData();
      data.append('portrait', this.$refs.fileInput.files[0]);
      data.append('username', this.user.username);
      axios.post(`${settings.ipAddress}/file/uploadPortrait`, data,
        {
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        }
      ).then(res => {
        alert('上传成功');
      }).catch(err => {
      
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.avatar-upload {
  border-radius: 3px;;
  position: fixed;
  top: 20vh;
  left: 15vw;
  width: 70vw;
  height: 80vw;
  background-color: #f2eccf;
  display: flex;
  justify-content: space-around;
  flex-direction: column;

  align-items: center;
  .update{
    width: 100px;
    height: 30px;
    background-color: #225400;
    font-size: 13px;
    font-weight: 600;
    text-align: center;
    line-height: 30px;
    border-radius: 4px;
    color: #ffffff;
  }
  .avatar-preview {
    width: 50vw;
    height: 50vw;
    border-radius: 50%;
    background-color: #f0f0f0;
    display: flex;
    justify-content: center;
    align-items: center;
    cursor: pointer;
    overflow: hidden;
    box-shadow: 0 0 5px rgba(0, 0, 0, 0.2);

    .preview-image {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }

    .fa-camera {
      font-size: 40px;
      color: #999;
    }
  }
}
</style>